package controllers

import (
	"comment/models"
	"comment/util"
	"regexp"

	"github.com/astaxie/beego"
)

type BaseController struct {
	beego.Controller
}

func (c *BaseController) Prepare() {
	url := c.Ctx.Request.RequestURI
	b, _ := regexp.MatchString("/api/*", url)
	if !b {
		user := c.GetSession("User")
		if user != nil {
			var permissions []*models.Permission
			permissions = models.FindPermissionByUser(user.(models.User).Id)
			c.Data["menu"] = permissions
			c.Data["userId"] = user.(models.User).Id
			c.Data["role"] = c.GetSession("Role")
			c.Data["user"] = user.(models.User)
		} else {
			if c.Ctx.Request.RequestURI != "/login" {
				c.Redirect("/login", 302)
			}
		}
	} else {
		count, _ := util.GetInt(c.Ctx.Input.IP())
		if count == 0 {
			util.Set(c.Ctx.Input.IP(), 1)
			time, _ := beego.AppConfig.Int("limit_time")
			util.Do("EXPIRE", c.Ctx.Input.IP(), time)
		} else {
			number, _ := beego.AppConfig.Int("limit_number")
			if count >= int(number) {
				c.Ctx.WriteString("请求频率超过上限")
			} else {
				util.Do("INCRBY", c.Ctx.Input.IP(), 1)
			}
		}
	}
}
